package com.zhangc.blog.admin.service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Sets;
import com.zhangc.blog.admin.mapper.AuthObjMapper;
import com.zhangc.blog.base.constants.RedisKeyConstants;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class AuthObjService {
    @Autowired
    AuthObjMapper authObjMapper;
    @Autowired
    RedisService redisService;

    @Value("${blog.redis.enable}")
    private boolean enableRedis;

    /**
     * 功能描述: <br>
     * 〈查询所有需要授权才能访问的资源〉
     *
     * @param
     * @return java.util.Set<java.lang.String>
     * @author wx:fdzhangc
     */
    public Set<String> queryAllAuthObj() {
        if (!enableRedis) {
            List<String> data = authObjMapper.getApiPaths();
            return new HashSet<>(data);
        }
        Long val = redisService.hsize(RedisKeyConstants.ALL_AUTH_OBJ);
        if (val == null || val.equals(0L)) {
            //没有缓存，查询库,并初始化缓存
            List<String> data = authObjMapper.getApiPaths();
            if (CollectionUtils.isEmpty(data)) {
                return Sets.newHashSet();
            }
            setAuthObjToRedis(data);
            return new HashSet<>(data);
        } else {
            //从缓存查
            return redisService.hmget(RedisKeyConstants.ALL_AUTH_OBJ).keySet().stream().map(Object::toString).collect(Collectors.toSet());
        }
    }

    private void setAuthObjToRedis(List<String> list) {
        Map<String, Object> map = list.stream().collect(Collectors.toMap(
                a -> a, a -> "1", (key1, key2) -> key2)
        );
        redisService.hmset(RedisKeyConstants.ALL_AUTH_OBJ, map);
    }
}
